package pers.duorhs.easierfeign.handler;

import com.alibaba.fastjson.JSON;
import lombok.Getter;
import lombok.Setter;
import pers.duorhs.easierfeign.config.EasierFeignClientsConfiguration;
import pers.duorhs.easierfeign.exception.RemoteInvokeException;
import pers.duorhs.easierfeign.iface.GeneralRemoteClient;

import java.util.List;

/**
 * @author Duorhs
 * @date 2022/1/10 14:39
 */
@Setter
@Getter
public class EasierFeignServiceHandler {

    /**
     * 把Client实体类和Name分离，可以在配置类中实现静态类构造handler，在构造函数后再具体指定client对象
     */
    private GeneralRemoteClient client = null;

    private String clientName;

    public EasierFeignServiceHandler(String clientName) {
        this.clientName = clientName;
    }

    private void checkClient() {
        if (this.client == null) {
            client = EasierFeignClientsConfiguration.clientMap.get(clientName);
        }
    }

    public <T> T handleResult(String serviceName, String methodName, Class<? extends T> clazz, Object... args) {
        checkClient();
        try {
            String result = client.remoteInvoke(serviceName, methodName, JSON.toJSONString(args));
            if (result.startsWith(RemoteInvokeException.PREFIX)) {
                throw JSON.parseObject(result, RemoteInvokeException.class);
            }
            return JSON.parseObject(result, clazz);
        } catch (RemoteInvokeException e) {
            e.printStackTrace();
            return null;
        }
    }

    public <T> List<? extends T> handleCollResult(String serviceName, String methodName, Class<? extends T> clazz, Object... args) {
        checkClient();
        try {
            String result = client.remoteInvoke(serviceName, methodName, JSON.toJSONString(args));
            if (result.startsWith(RemoteInvokeException.PREFIX)) {
                throw JSON.parseObject(result, RemoteInvokeException.class);
            }
            return JSON.parseArray(result, clazz);
        } catch (RemoteInvokeException e) {
            e.printStackTrace();
            return null;
        }
    }

}
